package org.wejob.web;


import org.wejob.web.connect.ConnectManager;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;

public class WebServer {
    //用于检测所有Channel状态的selector
    private Selector selector;
    private HashMap<String, SocketChannel> servers = HashMap.newHashMap(16);
    private ServerSocketChannel server;
    private ConnectManager connectManager;

    WebServer(int prot) throws IOException {
        this.selector = Selector.open();
        this.server = ServerSocketChannel.open();
        InetSocketAddress isa = new InetSocketAddress(8888);
        server.socket().bind(isa);
        server.configureBlocking(false);
        server.register(selector, SelectionKey.OP_ACCEPT);
        this.connectManager=new ConnectManager();
    }

    public void listen() throws IOException {
        while (selector.select() > 0) {
            for (SelectionKey sk : selector.selectedKeys()) {
                selector.selectedKeys().remove(sk);
                if (sk.isAcceptable()) {
                    connect();
                }
            }
        }
    }

    private void connect() throws IOException {
        SocketChannel sc=this.server.accept();
        servers.put(sc.getRemoteAddress().toString(),sc);
        assert this.connectManager!=null;
        this.connectManager.startConnect(new WebClient(sc));
    }

    public static void main(String[] args) throws IOException {
        new WebServer(8888).listen();
    }
}